package com.wnhoo.smartfishtank.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;

/**
 * Created by kevinwen on 2014/11/26.
 * Copyright (c) 2014/11/26.KevinWen. All rights reserved.
 */
public class ConnectionChangeReceiver extends BroadcastReceiver{
	private static final String TAG =ConnectionChangeReceiver.class.getSimpleName();  
	private static final String netACTION="android.net.conn.CONNECTIVITY_CHANGE";
	public static final int NETWORK_INIT = 0;
	public static final int NETWORK_WIFI = 1;
	public static final int NETWORK_MOBILE = 2;
	public static final int NETWORK_DISCONNECTED = 3;

	private boolean isNetworkStatus = true;
	private int networkType = NETWORK_INIT;


    @Override
    public void onReceive(Context context, Intent intent) {
        MyLog.i(TAG, "网络状态改变");

        boolean success = false;

        if(intent.getAction().equals(netACTION)){
            //Intent中ConnectivityManager.EXTRA_NO_CONNECTIVITY这个关键字表示着当前是否连接上了网络
            //true 代表网络断开   false 代表网络没有断开
            if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)){
                MyLog.e(TAG, "网络断开");
                isNetworkStatus = false;
            }else{
                MyLog.d(TAG, "网络正常");
                isNetworkStatus = true;
            }
        }
        try {
            //获得网络连接服务
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            // State state = connManager.getActiveNetworkInfo().getState();
            // 获取WIFI网络连接状态
            State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            // 判断是否正在使用WIFI网络

            if (State.CONNECTED == state) {
                success = true;
                MyLog.d(TAG, "当前网络是WIFI ");
                networkType = NETWORK_WIFI;
            }

            // 获取GPRS网络连接状态
            state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
            // 判断是否正在使用GPRS网络
            if (State.CONNECTED == state) {
                success = true;
                MyLog.d(TAG, "当前网络是MOBILE");
                networkType = NETWORK_MOBILE;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        if (!success) {
            //			Toast.makeText(context, context.getString(R.string.your_network_has_disconnected), Toast.LENGTH_LONG).show();
            MyLog.d(TAG, "当前网络是disconnected");
            networkType = NETWORK_DISCONNECTED;
        }
        MyLog.i(TAG, "---------------");
    }

    public boolean getNetworkStatus(){

        return isNetworkStatus;
    }


    public int getNetworkType(){

        return networkType;
    }
}